package com.agrimall.servlet.admin;

import com.agrimall.entity.Announcement;
import com.agrimall.entity.User;
import com.agrimall.mapper.AnnouncementMapper;
import com.agrimall.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

/**
 * 管理员公告管理Servlet
 */
@WebServlet("/admin/announcement")
public class AnnouncementManageServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        User admin = (User) session.getAttribute("admin");
        
        if (admin == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return;
        }
        
        // 公告列表
        listAnnouncements(request, response);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        User admin = (User) session.getAttribute("admin");
        
        if (admin == null) {
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.print("{\"success\":false,\"message\":\"未登录\"}");
            return;
        }
        
        String action = request.getParameter("action");
        
        if ("add".equals(action)) {
            addAnnouncement(request, response, admin);
        } else if ("update".equals(action)) {
            updateAnnouncement(request, response, admin);
        } else if ("delete".equals(action)) {
            deleteAnnouncement(request, response);
        } else if ("batchDelete".equals(action)) {
            batchDeleteAnnouncements(request, response);
        } else {
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.print("{\"success\":false,\"message\":\"无效的操作\"}");
        }
    }
    
    /**
     * 公告列表
     */
    private void listAnnouncements(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String pageStr = request.getParameter("page");
        String title = request.getParameter("title");
        String content = request.getParameter("content");
        String typeStr = request.getParameter("type");
        
        int page = 1;
        if (pageStr != null && !pageStr.isEmpty()) {
            try {
                page = Integer.parseInt(pageStr);
            } catch (NumberFormatException e) {
                page = 1;
            }
        }
        int pageSize = 10;
        
        Integer type = null;
        if (typeStr != null && !typeStr.trim().isEmpty()) {
            try {
                type = Integer.parseInt(typeStr.trim());
            } catch (NumberFormatException e) {
                type = null;
            }
        }
        
        List<Announcement> announcements;
        int totalCount = 0;
        
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        try {
            AnnouncementMapper mapper = sqlSession.getMapper(AnnouncementMapper.class);
            
            // 判断是否有查询条件
            boolean hasConditions = (title != null && !title.trim().isEmpty()) ||
                                   (content != null && !content.trim().isEmpty()) ||
                                   (type != null);
            
            if (hasConditions) {
                int offset = (page - 1) * pageSize;
                announcements = mapper.selectByConditions(
                    title != null ? title.trim() : null,
                    content != null ? content.trim() : null,
                    type,
                    offset,
                    pageSize
                );
                totalCount = mapper.countByConditions(
                    title != null ? title.trim() : null,
                    content != null ? content.trim() : null,
                    type
                );
            } else {
                int offset = (page - 1) * pageSize;
                announcements = mapper.selectAll(offset, pageSize);
                // 计算总数（需要添加countAll方法，暂时使用条件查询）
                totalCount = mapper.countByConditions(null, null, null);
            }
            
            if (announcements == null) {
                announcements = new java.util.ArrayList<>();
            }
        } catch (Exception e) {
            e.printStackTrace();
            announcements = new java.util.ArrayList<>();
            request.setAttribute("error", "查询公告失败：" + e.getMessage());
        } finally {
            sqlSession.close();
        }
        
        int totalPages = totalCount > 0 ? (int) Math.ceil((double) totalCount / pageSize) : 1;
        
        request.setAttribute("announcements", announcements);
        request.setAttribute("page", page);
        request.setAttribute("totalPages", totalPages);
        request.setAttribute("totalCount", totalCount);
        request.setAttribute("title", title);
        request.setAttribute("content", content);
        request.setAttribute("type", typeStr);
        
        request.getRequestDispatcher("/admin/announcement/list.jsp").forward(request, response);
    }
    
    /**
     * 添加公告
     */
    private void addAnnouncement(HttpServletRequest request, HttpServletResponse response, User admin)
            throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            String title = request.getParameter("title");
            String content = request.getParameter("content");
            String typeStr = request.getParameter("type");
            String statusStr = request.getParameter("status");
            
            // 验证
            if (title == null || title.trim().isEmpty()) {
                out.print("{\"success\":false,\"message\":\"标题不能为空\"}");
                return;
            }
            
            if (content == null || content.trim().isEmpty()) {
                out.print("{\"success\":false,\"message\":\"内容不能为空\"}");
                return;
            }
            
            Integer type = null;
            if (typeStr != null && !typeStr.trim().isEmpty()) {
                try {
                    type = Integer.parseInt(typeStr.trim());
                    if (type != 0 && type != 1) {
                        out.print("{\"success\":false,\"message\":\"类型无效（0-用户公告，1-商家公告）\"}");
                        return;
                    }
                } catch (NumberFormatException e) {
                    out.print("{\"success\":false,\"message\":\"类型格式错误\"}");
                    return;
                }
            } else {
                out.print("{\"success\":false,\"message\":\"类型不能为空\"}");
                return;
            }
            
            Integer status = 1; // 默认显示
            if (statusStr != null && !statusStr.trim().isEmpty()) {
                try {
                    status = Integer.parseInt(statusStr.trim());
                    if (status != 0 && status != 1) {
                        status = 1;
                    }
                } catch (NumberFormatException e) {
                    status = 1;
                }
            }
            
            Announcement announcement = new Announcement();
            announcement.setTitle(title.trim());
            announcement.setContent(content.trim());
            announcement.setAdminId(admin.getUserId());
            announcement.setType(type);
            announcement.setStatus(status);
            announcement.setCreateTime(new Date());
            announcement.setUpdateTime(new Date());
            
            SqlSession sqlSession = MyBatisUtil.getSqlSession();
            try {
                AnnouncementMapper mapper = sqlSession.getMapper(AnnouncementMapper.class);
                int result = mapper.insert(announcement);
                sqlSession.commit();
                
                if (result > 0) {
                    out.print("{\"success\":true,\"message\":\"添加成功\"}");
                } else {
                    out.print("{\"success\":false,\"message\":\"添加失败\"}");
                }
            } catch (Exception e) {
                sqlSession.rollback();
                e.printStackTrace();
                out.print("{\"success\":false,\"message\":\"添加失败：" + e.getMessage() + "\"}");
            } finally {
                sqlSession.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.print("{\"success\":false,\"message\":\"服务器错误：" + e.getMessage() + "\"}");
        } finally {
            out.flush();
            out.close();
        }
    }
    
    /**
     * 更新公告
     */
    private void updateAnnouncement(HttpServletRequest request, HttpServletResponse response, User admin)
            throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            String announcementIdStr = request.getParameter("announcementId");
            String title = request.getParameter("title");
            String content = request.getParameter("content");
            String typeStr = request.getParameter("type");
            String statusStr = request.getParameter("status");
            
            // 验证公告ID
            Long announcementId = null;
            if (announcementIdStr == null || announcementIdStr.trim().isEmpty()) {
                out.print("{\"success\":false,\"message\":\"公告ID不能为空\"}");
                return;
            }
            try {
                announcementId = Long.parseLong(announcementIdStr.trim());
            } catch (NumberFormatException e) {
                out.print("{\"success\":false,\"message\":\"公告ID格式错误\"}");
                return;
            }
            
            // 验证标题
            if (title == null || title.trim().isEmpty()) {
                out.print("{\"success\":false,\"message\":\"标题不能为空\"}");
                return;
            }
            
            // 验证内容
            if (content == null || content.trim().isEmpty()) {
                out.print("{\"success\":false,\"message\":\"内容不能为空\"}");
                return;
            }
            
            // 验证类型
            Integer type = null;
            if (typeStr != null && !typeStr.trim().isEmpty()) {
                try {
                    type = Integer.parseInt(typeStr.trim());
                    if (type != 0 && type != 1) {
                        out.print("{\"success\":false,\"message\":\"类型无效（0-用户公告，1-商家公告）\"}");
                        return;
                    }
                } catch (NumberFormatException e) {
                    out.print("{\"success\":false,\"message\":\"类型格式错误\"}");
                    return;
                }
            } else {
                out.print("{\"success\":false,\"message\":\"类型不能为空\"}");
                return;
            }
            
            // 验证状态
            Integer status = 1;
            if (statusStr != null && !statusStr.trim().isEmpty()) {
                try {
                    status = Integer.parseInt(statusStr.trim());
                    if (status != 0 && status != 1) {
                        status = 1;
                    }
                } catch (NumberFormatException e) {
                    status = 1;
                }
            }
            
            // 检查公告是否存在
            SqlSession sqlSession = MyBatisUtil.getSqlSession();
            try {
                AnnouncementMapper mapper = sqlSession.getMapper(AnnouncementMapper.class);
                Announcement existing = mapper.selectById(announcementId);
                
                if (existing == null) {
                    out.print("{\"success\":false,\"message\":\"公告不存在\"}");
                    return;
                }
                
                // 更新公告
                Announcement announcement = new Announcement();
                announcement.setAnnouncementId(announcementId);
                announcement.setTitle(title.trim());
                announcement.setContent(content.trim());
                announcement.setType(type);
                announcement.setStatus(status);
                announcement.setUpdateTime(new Date());
                
                int result = mapper.update(announcement);
                sqlSession.commit();
                
                if (result > 0) {
                    out.print("{\"success\":true,\"message\":\"更新成功\"}");
                } else {
                    out.print("{\"success\":false,\"message\":\"更新失败\"}");
                }
            } catch (Exception e) {
                sqlSession.rollback();
                e.printStackTrace();
                out.print("{\"success\":false,\"message\":\"更新失败：" + e.getMessage() + "\"}");
            } finally {
                sqlSession.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.print("{\"success\":false,\"message\":\"服务器错误：" + e.getMessage() + "\"}");
        } finally {
            out.flush();
            out.close();
        }
    }
    
    /**
     * 删除公告
     */
    private void deleteAnnouncement(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            String announcementIdStr = request.getParameter("announcementId");
            
            if (announcementIdStr == null || announcementIdStr.trim().isEmpty()) {
                out.print("{\"success\":false,\"message\":\"公告ID不能为空\"}");
                return;
            }
            
            Long announcementId;
            try {
                announcementId = Long.parseLong(announcementIdStr.trim());
            } catch (NumberFormatException e) {
                out.print("{\"success\":false,\"message\":\"公告ID格式错误\"}");
                return;
            }
            
            SqlSession sqlSession = MyBatisUtil.getSqlSession();
            try {
                AnnouncementMapper mapper = sqlSession.getMapper(AnnouncementMapper.class);
                int result = mapper.delete(announcementId);
                sqlSession.commit();
                
                if (result > 0) {
                    out.print("{\"success\":true,\"message\":\"删除成功\"}");
                } else {
                    out.print("{\"success\":false,\"message\":\"删除失败，公告可能不存在\"}");
                }
            } catch (Exception e) {
                sqlSession.rollback();
                e.printStackTrace();
                out.print("{\"success\":false,\"message\":\"删除失败：" + e.getMessage() + "\"}");
            } finally {
                sqlSession.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.print("{\"success\":false,\"message\":\"服务器错误：" + e.getMessage() + "\"}");
        } finally {
            out.flush();
            out.close();
        }
    }
    
    /**
     * 批量删除公告
     */
    private void batchDeleteAnnouncements(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            String[] announcementIdStrs = request.getParameterValues("announcementIds[]");
            
            if (announcementIdStrs == null || announcementIdStrs.length == 0) {
                out.print("{\"success\":false,\"message\":\"请选择要删除的公告\"}");
                return;
            }
            
            List<Long> announcementIds = new java.util.ArrayList<>();
            for (String announcementIdStr : announcementIdStrs) {
                try {
                    Long announcementId = Long.parseLong(announcementIdStr.trim());
                    announcementIds.add(announcementId);
                } catch (NumberFormatException e) {
                    // 忽略无效的ID
                }
            }
            
            if (announcementIds.isEmpty()) {
                out.print("{\"success\":false,\"message\":\"没有有效的公告ID\"}");
                return;
            }
            
            int successCount = 0;
            int failCount = 0;
            
            SqlSession sqlSession = MyBatisUtil.getSqlSession();
            try {
                AnnouncementMapper mapper = sqlSession.getMapper(AnnouncementMapper.class);
                
                for (Long announcementId : announcementIds) {
                    try {
                        int result = mapper.delete(announcementId);
                        if (result > 0) {
                            successCount++;
                        } else {
                            failCount++;
                        }
                    } catch (Exception e) {
                        failCount++;
                    }
                }
                
                sqlSession.commit();
            } catch (Exception e) {
                sqlSession.rollback();
                e.printStackTrace();
                out.print("{\"success\":false,\"message\":\"删除失败：" + e.getMessage() + "\"}");
                return;
            } finally {
                sqlSession.close();
            }
            
            if (failCount == 0) {
                out.print("{\"success\":true,\"message\":\"成功删除 " + successCount + " 个公告\"}");
            } else {
                out.print("{\"success\":true,\"message\":\"成功删除 " + successCount + " 个公告，失败 " + failCount + " 个\"}");
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.print("{\"success\":false,\"message\":\"服务器错误：" + e.getMessage() + "\"}");
        } finally {
            out.flush();
            out.close();
        }
    }
}

